
  /**
   * 获取截图中的组件剪裁图
   * 可用作透明背景
   * 返回图片image对象
   * 代码改自：https://gist.github.com/mzeryck/3a97ccd1e059b3afa3c6666d27a496c9
   * @param {string} title 开始处理前提示用户截图的信息，可选（适合用在组件自定义透明背景时提示）
   */
  const getWidgetScreenShot = async (buttonState) => {
  	let img = loadImgCache("BACKGROUND_IMAGE");
  	let phone;
  	let flag = true;
  	if(img){
      let message = "发现使用的空白界面截图，是否选择使用？";
      let exitOptions = ['确认使用', '不选择 >'];
      let shouldExit = await generateAlert(message, exitOptions);
      if (!shouldExit) flag = false;
      let height = img.size.height;
      phone = phoneSizes()[height];
    }
    if(flag){
      let message = '开始之前，请先前往桌面，截取空白界面的截图。然后回来继续';
      let exitOptions = ['我已截图', '前去截图 >'];
      let shouldExit = await generateAlert(message, exitOptions);
      if (shouldExit) return;
      // Get screenshot and determine phone size.
      img = await Photos.fromLibrary();
      let height = img.size.height;
      phone = phoneSizes()[height];
      if (!phone) {
      	message = '好像您选择的照片不是正确的截图，请先前往桌面';
      	await generateAlert(message, ['我已知晓']);
      	return;
      }
      saveImgCache("BACKGROUND_IMAGE", img);
  	}
    // Prompt for widget size and position.
    let message = '截图中要设置透明背景组件的尺寸类型是？';
    let sizes = ['小尺寸', '中尺寸', '大尺寸'];
    let size = await generateAlert(message, sizes);
    let widgetSize = sizes[size];

    message = '要设置透明背景的小组件在哪个位置？';
    // Determine image crop based on phone size.
    let crop = { w: '', h: '', x: '', y: '' };
    if (widgetSize === '小尺寸') {
      crop.w = phone.small;
      crop.h = phone.small;
      let positions = ['左上角','右上角','中间左','中间右','左下角','右下角'];
      let _posotions = ['Top left','Top right','Middle left','Middle right','Bottom left','Bottom right'];
      let position = await generateAlert(message, positions);

      // Convert the two words into two keys for the phone size dictionary.
      let keys = _posotions[position].toLowerCase().split(' ');
      crop.y = phone[keys[0]];
      crop.x = phone[keys[1]];
    } else if (widgetSize === '中尺寸') {
      crop.w = phone.medium;
      crop.h = phone.small;

      // Medium and large widgets have a fixed x-value.
      crop.x = phone.left;
      let positions = ['顶部', '中间', '底部'];
      let _positions = ['Top', 'Middle', 'Bottom'];
      let position = await generateAlert(message, positions);
      let key = _positions[position].toLowerCase();
      crop.y = phone[key];
    } else if (widgetSize === '大尺寸') {
      crop.w = phone.medium;
      crop.h = phone.large;
      crop.x = phone.left;
      let positions = ['顶部', '底部'];
      let position = await generateAlert(message, positions);
      // Large widgets at the bottom have the "middle" y-value.
      crop.y = position ? phone.middle : phone.top;
    }
    if(buttonState) crop.y = crop.y + 18;
    // Crop image and finalize the widget.
    return cropImage(img, new Rect(crop.x, crop.y, crop.w, crop.h));
  }
  
  // 所有支持手机上小部件的像素大小和位置。
  const phoneSizes = () => {
    return {
      // 14 Pro Max
      2796: {small: 510,medium: 1092,large: 1146,left: 99,right: 681,top: 282,middle: 918,bottom: 1554},
      // 14 Pro
      2556: {small: 474,medium: 1014,large: 1062,left: 82,right: 622,top: 270,middle: 858,bottom: 1446},
      // 13 Pro Max, 12 Pro Max
      2778: {small: 510,medium: 1092,large: 1146,left: 96,right: 678,top: 246,middle: 882,bottom: 1518},
      // 12 and 12 Pro
      2532: {small: 474,medium: 1014,large: 1062,left: 78,right: 618,top: 231,middle: 819,bottom: 1407},
      // 11 Pro Max, XS Max
      2688: {small: 507,medium: 1080,large: 1137,left: 81,right: 654,top: 228,middle: 858,bottom: 1488},
      // 11, XR
      1792: {small: 338,medium: 720,large: 758,left: 54,right: 436,top: 160,middle: 580,bottom: 1000},
      // 11 Pro, XS, X
      2436: {small: 465,medium: 987,large: 1035,left: 69,right: 591,top: 213,middle: 783,bottom: 1353},
      // Plus phones
      2208: {small: 471,medium: 1044,large: 1071,left: 99,right: 672,top: 114,middle: 696,bottom: 1278},
      // SE2 and 6/6S/7/8
      1334: {small: 296,medium: 642,large: 648,left: 54,right: 400,top: 60,middle: 412,bottom: 764},
      // SE1
      1136: {small: 282,medium: 584,large: 622,left: 30,right: 332,top: 59,middle: 399,bottom: 399},
      // 11 and XR in Display Zoom mode
      1624: {small: 310,medium: 658,large: 690,left: 46,right: 394,top: 142,middle: 522,bottom: 902},
      // Plus in Display Zoom mode
      2001: {small: 444,medium: 963,large: 972,left: 81,right: 600,top: 90,middle: 618,bottom: 1146},
    };
  }
  
  FM = FileManager.local();
  MGR_DOCU = FM.libraryDirectory();
  IMAGE_FOLDER = FM.joinPath(
    MGR_DOCU, 'images/'
  );
  
  const saveImgCache = (cacheKey, img, path = IMAGE_FOLDER) => {
    const cacheFile = FM.joinPath(path, `${cacheKey}.png`);
    FM.writeImage(cacheFile, img);
  }

  const loadImgCache = (cacheKey, path = IMAGE_FOLDER) => {
    const cacheFile = FM.joinPath(path, `${cacheKey}.png`);
    const fileExists = FM.fileExists(cacheFile);
    let img = undefined;
    if (fileExists) {
      img = Image.fromFile(cacheFile);
    }
    return img;
  }
  
  // 图像裁剪
  const cropImage = (img, rect) => {
    let draw = new DrawContext();
    draw.size = new Size(rect.width, rect.height);
    draw.drawImageAtPoint(img, new Point(-rect.x, -rect.y));
    return draw.getImage();
  }
  
  
  const generateAlert = async (message, options, title) => {
    let alert = new Alert();
    title && (alert.title = title);
    alert.message = title ? '\n' + message : message;
    if(options) {
      for (const option of options) {
        alert.addAction(option);
      }
    }
    return await alert.presentAlert();
  }
  
  module.exports = getWidgetScreenShot;